﻿using CommunityToolkit.Mvvm.Input;
using CommunityToolkit.Mvvm.Messaging.Messages;
using CommunityToolkit.Mvvm.Messaging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using HsServerHa.Entity.Models;
using HsServerHa.Utility.DataHelper;
using HsServerHa.Utility.SQLite;
using System.Collections.ObjectModel;
using System.Data;
using HsServerHa.UserControls.Dialog;
using HsServerHa.WinPage;
using CommunityToolkit.Mvvm.ComponentModel;
using AduSkin.Controls.Metro;
using System.Windows;
using HsServerHa.Common.Auth;
using System.Configuration;
using System.Net.Http.Headers;
using AduSkin.Utility;
using HsServerHa.Utility.HttpHelper;
using Newtonsoft.Json;
using HsServerHa.Core.Http;
using HsServerHa.Utility.NetWork;

namespace HsServerHa.ViewModel
{
    public class MultipleNetworkCardSettingViewModel : ObservableObject
    {

        public RelayCommand AddCommand { get; set; }
        public RelayCommand QueryCommand { get; set; }
        public RelayCommand<object> UpdateCommand { get; set; }
        public RelayCommand<object> DelCommand { get; set; }
        public MultipleNetworkCardSettingViewModel() {
            AddCommand = new RelayCommand(addFun);
            QueryCommand = new RelayCommand(InitData);
            UpdateCommand = new RelayCommand<object>(updateFun);
            DelCommand = new RelayCommand<object>(DelFun);
            InitData();
            WeakReferenceMessenger.Default.Register<ValueChangedMessage<string>, string>(this, "RefreshNetworkCard", (r, message) =>
            {
                if (message != null)
                {
                    if (message.Value == "刷新多网卡数据")
                    {
                        InitData();
                    }
                }
            });
        }

        public  void InitData() {
            //var dataSet = DbHelperSQLite.Query("SELECT * FROM MultipleNetworkCardManage ", null);
            //DataTable dt = dataSet.Tables[0];
            //List<MultipleNetworkCardManageEntity> list = DataHelpers.ConvertToModel<MultipleNetworkCardManageEntity>(dt);

            var list=SQLiteHelper.Table<MultipleNetworkCardManageEntity>().ToList();
            CardList = new ObservableCollection<MultipleNetworkCardManageEntity>(list);
        }

        public ObservableCollection<MultipleNetworkCardManageEntity> cardList { get; set; }
        public ObservableCollection<MultipleNetworkCardManageEntity> CardList
        {
            get { return cardList; }
            set
            {
                cardList = value;
                OnPropertyChanged("CardList");
            }
        }

        public void addFun()
        {
            #region 授权验证
            if (!AuthorizationVerification.IsVerification())
            {
                AduMessageBoxs.Show("授权到期！");
                return;
            }

            #endregion
            AlertTemp alertTempJoinMaster = new AlertTemp(new AddMultipleCard(), "添加多网卡", "500", "800");
            alertTempJoinMaster.ShowDialog();
        }

        public async void DelFun(object Id) {
            #region 授权验证
            if (!AuthorizationVerification.IsVerification())
            {
                AduMessageBoxs.Show("授权到期！");
                return;
            }

            #endregion

            var first = CardList.FirstOrDefault(x => x.Id == long.Parse(Id?.ToString()));
            if (first == null)
            {
                AduMessageBoxs.Show("删除失败，数据不存在！");
                return;
            }
            MessageBoxResult dr = AduMessageBox.ShowOKCancel($"你确定删除吗？", "系统提示!", "确定", "取消");
            if (dr == MessageBoxResult.OK)
            {

                //var sqlMaster2 = "SELECT * FROM  MasterSlaveBind where 1=1";
                //var dtMaster2 = DbHelperSQLite.Query(sqlMaster2)?.Tables?[0];
                //var masterList = DataHelpers.ConvertToModel<MasterSlaveBindEntity>(dtMaster2);

                var masterList = await SQLiteHelper.TableAsync<MasterSlaveBindEntity>().ToListAsync().ConfigureAwait(false);
                var masterFirst = masterList.FirstOrDefault();
                var masterPath = "";
                if (masterFirst == null)
                {
                    AduMessageBoxs.Show("系统设置错误！");
                    return;
                }
                if (App.isMaster.Value)
                {
                    if (string.IsNullOrEmpty(masterFirst.SlaveIP))
                    {
                        AduMessageBoxs.Show("主从未联机，请检查后再设置！");
                        return;
                    }
                    masterPath = $"http://{masterFirst.SlaveIP}:{ConfigurationManager.AppSettings["HttpPort"]?.ToString() ?? "6601"}/";

                }
                else
                {
                    masterPath = $"http://{masterFirst.MasterIP}:{ConfigurationManager.AppSettings["HttpPort"]?.ToString() ?? "6601"}/";
                }
                var result = await HttpHelpers.PostToJson<HttpResponseResultModel<object>>(masterPath + $"{ConfigurationManager.AppSettings["DeleteMulttipRemoteCardInfo"]?.ToString() ?? "DeleteMulttipRemoteCardInfo"}", JsonConvert.SerializeObject(first)).ConfigureAwait(false);
                if (result == null || !result.IsSuccess)
                {
                    AduMessageBoxs.Show("删除失败");
                    return;
                }
                var i = SQLiteHelper.ExecuteSql($"delete from MultipleNetworkCardManage where ProgramKey='{first.ProgramKey}' ");
                //var i= SQLiteHelper.Delete(first);
                NetWorkHelper.DeleteVirtualIP(first.VirtuallyIP);
                if (i > 0)
                {
                    AduMessageBoxs.Show("删除成功！");
                    InitData();
                    return;
                }
                else
                {
                    AduMessageBoxs.Show("删除失败");
                    return;
                }
            }
        }

        public void updateFun(object Id)
        {
            #region 授权验证
            if (!AuthorizationVerification.IsVerification())
            {
                AduMessageBoxs.Show("授权到期！");
                return;
            }

            #endregion
            AlertTemp alertTempJoinMaster = new AlertTemp(new UpdateMultipleCard(long.Parse(Id?.ToString()??"0")), "修改多网卡", "500", "800");
            alertTempJoinMaster.ShowDialog();
        }
    }
}
